package com.crm.system.controller;

import com.crm.common.util.VerifyCodeUtil;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @Author yincuimei
 * @Date 2020/12/17 14:49
 */
@Controller
@RequestMapping("/captcha")
@Slf4j
public class SysCaptchaController {
    /*
     *获取验证码图片
     */
    @RequestMapping(value = "/createVerifyImg")
    public void getVerificationCode(HttpServletResponse response,HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession();
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        //获取验证码图片
        String verifyCode = VerifyCodeUtil.generateVerifyCode(4);
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, verifyCode);
        ServletOutputStream out = response.getOutputStream();
        VerifyCodeUtil.outputImage(120,35,out,verifyCode);
        try {
            out.flush();
        } catch (IOException e) {
            log.error("captcha createVerifyImg error:", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}
